using System;
using CommunityServer.Components;
using System.Collections;
using CommunityServer.Galleries.Components;

namespace CommunityServer.Galleries.Controls
{
	/// <summary>
	/// Summary description for InlineTagEditor.
	/// </summary>
	public class InlineTagEditor : CommunityServer.Controls.InlineTagEditor
	{
		CSContext csContext = CSContext.Current;

		public override void SaveTags(int postID, string[] tags)
		{
			if (this.IsEditable(postID))
			{
				GalleryPost post = GalleryPosts.GetPicture(postID);
				post.Categories =  tags;
				GalleryPosts.UpdatePicture(post);
			}
		}

		public override string GetUrl(string tag)
		{
			return GalleryUrls.Instance().TagsBrowser(this.Gallery.ApplicationKey, new string[] { tag });
		}

		public override bool IsEditable (int postID)
		{
			return IsEditable();
		}

		public override bool IsEditable()
		{
			return Permissions.ValidatePermissions(this.Gallery, Permission.Post, csContext.User);
		}

		public override bool Visible
		{
			get
			{
				if (this.Gallery.CategorizationType != CategorizationType.Tag)
					return false;
				else
					return base.Visible;
			}
			set
			{
				base.Visible = value;
			}
		}

		Gallery _gallery = null;
		public virtual Gallery Gallery
		{
			get
			{
				if(_gallery == null)
				{
					string appKey = CSContext.Current.ApplicationKey;
					if(Globals.IsNullorEmpty(appKey))
						appKey = GalleryConfiguration.Instance().DefautApplicationKey;

					_gallery = Galleries.GetGallery(appKey);
				}

				return _gallery;
			}
			set
			{
				_gallery = value;
				_availableTags = null;
			}
		}

		string[] _availableTags = null;
		public override string[] AvailableTags 
		{ 
			get
			{
				if (_availableTags == null)
				{
					ArrayList allTags = PostCategories.GetCategories(this.Gallery.SectionID, true, false);
					ArrayList availableTags = new ArrayList();
					foreach (PostCategory pc in allTags)
					{
						availableTags.Add(pc.Name);
					}

					_availableTags = (string[]) availableTags.ToArray(typeof(string));
				}

				return _availableTags;
			}
		}
	}
}
